/*================================================================
*   Copyright (C) 2024 baichao All rights reserved.
*
*   文件名称：_thread.c
*   创 建 者：baichao
*   创建日期：2024年03月27日
*   描    述：到现在为止我还是没发现这个线程局部存储到底有什么典型的应用场景。
             反正给我的感觉是它能做到的局部变量都能做到，而且还不用考虑线程安全性问题，并且局部变量性能更好。
*
================================================================*/

#include <malloc.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
__thread FILE *thread_log = NULL;

void write_to_thread_log(const char *message) {
  fprintf(thread_log, "%s\n", message);
}

void *thread_function(void *args) {
  char thread_log_filename[128];
  sprintf(thread_log_filename, "thread%ld.log", (unsigned long)pthread_self());
  thread_log = fopen(thread_log_filename, "w");
  write_to_thread_log("Thread starting.");
  fclose(thread_log);
  return NULL;
}

int main() {
  int i;
  pthread_t threads[5];
  for (i = 0; i < 5; ++i)
    pthread_create(&(threads[i]), NULL, thread_function, NULL);
  for (i = 0; i < 5; ++i) pthread_join(threads[i], NULL);
  return 0;
}
